package com.dormitory.activity;

import android.app.Activity;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.dormitory.R;
import com.dormitory.adapter.ExpandableListAdapter;
import com.dormitory.application.MyApplication;
import com.dormitory.bean.DormitoryBean;
import com.dormitory.bean.FileBean;
import com.dormitory.bean.UserBean;
import com.dormitory.controller.FileController;
import com.dormitory.staticVariable.StaticVariable;
import com.kidyone.filepass.FilePassActivity;
import com.melnykov.fab.FloatingActionButton;
import com.nononsenseapps.filepicker.FilePickerActivity;
import com.nononsenseapps.filepicker.Utils;

import java.io.File;
import java.util.List;

public class FileActivity extends AppCompatActivity {

    private ExpandableListView mFileList;
    private ExpandableListAdapter mFileListAdapter;
    private FloatingActionButton mFab;
    private PopupWindow mPopupWindow;
    private View rootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file);

        mFileList = (ExpandableListView) findViewById(R.id.file_list);
        mFileList.setGroupIndicator(null);
        mFileList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                FileBean file = mFileListAdapter.getFileBean(groupPosition, childPosition);
                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(StaticVariable.DOWNLOADFILE_SERVLET+"?id="+file.getId()));
                request.setDestinationInExternalPublicDir("/dormitoryDownload/", file.getFileName());
                request.setTitle("正在下载"+file.getFileName());
                DownloadManager downloadManager= (DownloadManager) FileActivity.this.getSystemService(Context.DOWNLOAD_SERVICE);
                downloadManager.enqueue(request);
                Toast.makeText(FileActivity.this, "正在下载", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        mFileList.setAdapter(mFileListAdapter = new ExpandableListAdapter(this));

        (mFab = (FloatingActionButton)findViewById(R.id.fab)).attachToListView((ExpandableListView)findViewById(R.id.file_list));
        mFab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*Intent intent = new Intent(FileActivity.this, UploadFileActivity.class);
                startActivity(intent);*/
                mPopupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
            }
        });
        DormitoryBean dormitoryBean = ((MyApplication)getApplication()).getDormitory();
        if(dormitoryBean != null) {
            GetFileListAsyncTask getFileListAsyncTask = new GetFileListAsyncTask();
            getFileListAsyncTask.execute(dormitoryBean.getId());
        }
        initPopupWindow();
    }
    private void initPopupWindow() {
        View contentView = LayoutInflater.from(FileActivity.this)
                .inflate(R.layout.popup_window_file, null);

        mPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setContentView(contentView);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));

        rootView = LayoutInflater.from(FileActivity.this)  //把弹出菜单加到当前activity的layout中
                .inflate(R.layout.activity_file, null);

        View popBackground = contentView.findViewById(R.id.pop_background);
        View takePhoto = contentView.findViewById(R.id.upload_file);
        View fromPhotoGraph = contentView.findViewById(R.id.file_pass);
        View popCancel = contentView.findViewById(R.id.pop_cancel);
        View.OnClickListener onClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch(v.getId()) {
                    case R.id.upload_file:
                        Intent intent = new Intent(FileActivity.this, FilePickerActivity.class);
                        intent.putExtra(FilePickerActivity.EXTRA_ALLOW_MULTIPLE, false);
                        intent.putExtra(FilePickerActivity.EXTRA_ALLOW_CREATE_DIR, false);
                        intent.putExtra(FilePickerActivity.EXTRA_MODE, FilePickerActivity.MODE_FILE);
                        intent.putExtra(FilePickerActivity.EXTRA_START_PATH, Environment.getExternalStorageDirectory().getPath());
                        startActivityForResult(intent, 10086);
                        mPopupWindow.dismiss();
                        break;
                    case R.id.file_pass:
                        Intent intent2 = new Intent(FileActivity.this, FilePassActivity.class);
                        startActivity(intent2);
                        mPopupWindow.dismiss();
                        break;
                    case R.id.pop_background:
                    case R.id.pop_cancel:
                        mPopupWindow.dismiss();
                        break;
                }
            }
        };
        popBackground.setOnClickListener(onClickListener);
        takePhoto.setOnClickListener(onClickListener);
        fromPhotoGraph.setOnClickListener(onClickListener);
        popCancel.setOnClickListener(onClickListener);
    }

    private class GetFileListAsyncTask extends AsyncTask<Integer, Object, List<List<FileBean>>> {

        @Override
        protected List<List<FileBean>> doInBackground(Integer[] params) {
            FileController fileController = FileController.getInstance();
            return fileController.getFileList(params[0]);
        }

        @Override
        protected void onPostExecute(List<List<FileBean>> list) {
            super.onPostExecute(list);
            if(list != null)
                mFileListAdapter.updateList(list);
        }

    }

    private class UploadAsyncTask extends AsyncTask<Object, Object, Boolean> {

        private UserBean user;
        ProgressDialog progressDialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = new ProgressDialog(FileActivity.this);
            progressDialog.setTitle("上传中");
            progressDialog.setIndeterminate(true);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

        @Override
        protected Boolean doInBackground(Object[] params) {
            FileController fileController = FileController.getInstance();
            return fileController.uploadFile((File)params[0], (String)params[1], (Integer)params[2], (Boolean)params[3]);
        }

        @Override
        protected void onPostExecute(Boolean code) {
            super.onPostExecute(code);
            if(progressDialog != null && progressDialog.isShowing()) {
                progressDialog.cancel();
            }
            DormitoryBean dormitoryBean = ((MyApplication)getApplication()).getDormitory();
            if(dormitoryBean != null) {
                GetFileListAsyncTask getFileListAsyncTask = new GetFileListAsyncTask();
                getFileListAsyncTask.execute(dormitoryBean.getId());
            }
            if(code) {
                Toast.makeText(FileActivity.this, "上传成功", Toast.LENGTH_SHORT).show();
            }
            else {
                Toast.makeText(FileActivity.this, "上传失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 10086 && resultCode == Activity.RESULT_OK) {
            List<Uri> files = Utils.getSelectedFilesFromResult(data);
            for(Uri uri: files) {
                File file = Utils.getFileForUri(uri);
                UserBean user = ((MyApplication)getApplication()).getUser();
                DormitoryBean dormitory = ((MyApplication)getApplication()).getDormitory();
                if(user != null && dormitory != null) {
                    UploadAsyncTask uploadAsyncTask = new UploadAsyncTask();
                    uploadAsyncTask.execute(file, user.getName(), dormitory.getId(), true);
                }
            }
        }
    }
}
